<?php
/*
	微信小程序接口
*/
define('IN','custom');
require_once '../core/core.php';
$uniacid=intval($_POST['uniacid']);
$wxapp_id=intval($_POST['wxapp_id']);
if(!$wxapp_id || !$uniacid){
	exi('访问错误，关键参数缺失！','error');
}
$account=pdo_get('core_accounts',array('uniacid'=>$uniacid));
$wxapp=pdo_get('core_account_wxapp',array('id'=>$wxapp_id,'uniacid'=>$uniacid));
if(!$account || !$wxapp){
	exi('访问错误，找不到指定站点或者支付宝小程序！','error');
}
$_SESSION['uniacid']=$uniacid;
$_SESSION['wxapp_id']=$wxapp_id;
$_SESSION['token']=$_SESSION['token']?:random(30);
$_SESSION['base_key_str']=$_SESSION['base_key_str']?:str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-_');
if($_POST['code'] && $wxapp['appid'] && $wxapp['appsecret']){
	$url='https://api.weixin.qq.com/sns/jscode2session?appid='.$wxapp['appid'].'&secret='.$wxapp['appsecret'].'&js_code='.$_POST['code'].'&grant_type=authorization_code';
	$result=cfc('http')->ihttp_get($url);
	if(is_error($result)){
		exi('获取粉丝信息失败：'.$result['message'],'error');
	}
	$result=json_decode($result['content'],true);
	if($result['openid']){
		$_SESSION['openid']=$result['openid'];
		$_SESSION['session_key']=$result['session_key'];
		$mid=false;
		if($result['unionid']){
			$_SESSION['unionid']=$result['unionid'];
			$mid=pdo_getcolumn('core_members',array('unionid'=>$result['unionid'],'uniacid'=>$_SESSION['uniacid']),'id');
		}
		$fans=pdo_get('core_fans',array('openid'=>$_SESSION['openid'],'uniacid'=>$_SESSION['uniacid'],'type'=>1,'wxgid'=>$_SESSION['wxapp_id']),array('id','mid'));
		if($fans){
			if(!$mid && $fans['mid']){
				$mid= $fans['mid'];
			}
		}else{
			$fansdata=array(
				'uniacid'=>$_SESSION['uniacid'],
				'wxgid'=>$_SESSION['wxapp_id'],
				'openid'=>$_SESSION['openid'],
				'type'=>1,
				'createtime' => TIMESTAMP,
			);
			if($mid){
				$fansdata['mid']=$mid;
			}
			if($result['unionid']){
				$fansdata['unionid']=$result['unionid'];
			}
			pdo_insert('core_fans',$fansdata);
		}
		if($mid){
			model('core/member')->login($mid);
		}
	}
}
$res=array(
	'session_id'=>session_id(),
	'token'=>$_SESSION['token'],
	'base_key_str'=>$_SESSION['base_key_str'],
	'openid'=>$_SESSION['openid'],
	'uid'=>$_SESSION['uid'],
);
exi($res);